package com.wwl.cms.utils;


import com.wwl.cms.dto.CSVData;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wwl
 * @version 1.0
 * @date 2022/3/5 20:46
 * @description:
 */
public class CsvUtils {
    public static BufferedReader reader;
    public static BufferedWriter bw;
    public static AtomicInteger linkNumber = new AtomicInteger(0) ;
    public static void closeAll() {
        try {
            if(reader != null)
                reader.close();
            if(bw != null)
                bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 读取CSV格式的文档数据
     * @param filePath CSV格式的文件路劲
     * @return dataList csv数据读取放入二维list中。
     */

    public static List<List<String>> readCSVFileData(String filePath){
        List<List<String>> dataList=new ArrayList<>();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
        }catch(FileNotFoundException | UnsupportedEncodingException e){
            e.printStackTrace();
        }
        try{
            String line=null;
            while ((line=reader.readLine())!=null){
                String aa[]=line.split(",");
                List<String> cellList= Arrays.asList(aa);
                dataList.add(cellList);
            }
            closeAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    /*public static List<csvData>  readData(String filePath){
        List<List<String>> dataList=readCSVFileData(filePath);
        System.out.println(dataList);
        List<csvData> csvList=new ArrayList<>();
        for(int i = 0; i<dataList.size(); i++){
            if(i !=0) {
                csvData data=new csvData();
                data.setId(Integer.parseInt(dataList.get(i).get(0)));
                data.setName(dataList.get(i).get(1));
                data.setAge(Integer.parseInt(dataList.get(i).get(2)));
                csvList.add(data);
            }
        }
        return csvList;
    }*/
    /**
     * 读取CSV格式的文档数据
     * @param filePath CSV格式的文件路劲
     * @param data 需要写入的数据
     * @return dataList csv数据读取放入二维list中。
     */
    public static void writeCSVFileData(String filePath, CSVData data){
        try {
            bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"));
            if(linkNumber.get()==0){
                bw.write("ID"+","+"内容"+","+"描述");
                bw.newLine();
                linkNumber.incrementAndGet();
            }
            bw.write(data.getId()+","+data.getContent()+","+data.getDesc());
            bw.newLine();
            bw.flush();
            closeAll();
        } catch (Exception e) {
            closeAll();
            e.printStackTrace();
            System.exit(0);
        }
    }
}
